package com.lsp.microcommon.utils;

import com.lsp.microcommon.config.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * minio工具类
 */
@Component
public class MinioUtil {

//    @Value("${minio.bucketName}")
//    private String bucketName;
//
    @Resource
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 判断bucket是否存在，不存在则创建
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     *
     * @param
     * @return
     */
    public String upload(InputStream inputStream,String fileName,String contentType) {

        // 如果桶不存在，直接创建
        existBucket(minioProperties.getBucketName());

        InputStream in = null;
        try {
            // 上传到minio
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName()) //.bucket("img/" + bucketName)
//                    .object(fileName)默认上传到bucket下
                    .object("img/" + fileName)
                    .stream(inputStream, inputStream.available(), -1)
                    .contentType(contentType)
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回上传的文件名
        return String.format("%s/%s/%s%s",
                minioProperties.getEndpoint(),
                minioProperties.getBucketName(),
                "img/",
                fileName);
    }


}